<template>
  <div class="item-group-container">
    <!-- 顶部操作区域 -->
    <div class="top-section">
      <transition name="search-slide">
        <div class="search-area" v-show="showSearchArea">
          <div class="search-status" v-if="hasSearchConditions">
            <el-tag size="small" type="info">
              当前搜索条件: {{ getSearchConditionsText() }}
            </el-tag>
            <el-tag size="small" type="success" style="margin-left: 10px;">
              找到 {{ total }} 条结果
            </el-tag>
          </div>
          <el-input v-model="searchForm.itemCode" placeholder="请输入群组编码" class="search-input" clearable
            @keyup.enter="handleSearch" />
          <el-input v-model="searchForm.itemName" placeholder="请输入群组名称" class="search-input" clearable
            @keyup.enter="handleSearch" />

          <el-select v-model="searchForm.itemTypeId" placeholder="请选择群组类型" class="search-input" clearable
            @change="handleSearch">

            <el-option v-for="item in groupTypes" :key="item.id" :label="item.groupTypeName" :value="item.id" />
          </el-select>
          <el-button type="primary" @click="handleSearch" class="search-btn">
            <el-icon>
              <Search />
            </el-icon>
            搜索
          </el-button>
          <el-button @click="clearSearch" class="clear-btn">
            <el-icon>
              <Close />
            </el-icon>
            清空
          </el-button>
          <el-dropdown @command="loadSearchHistory" v-if="searchHistory.length > 0">
            <el-button class="history-btn">
              <el-icon>
                <Clock />
              </el-icon>
              历史
              <el-icon class="el-icon--right">
                <ArrowDown />
              </el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item v-for="(item, index) in searchHistory" :key="index" :command="item">
                  {{ getSearchHistoryText(item) }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </transition>
      <div class="action-buttons">
        <el-button type="primary" @click="handleAdd" class="action-btn">
          <el-icon>
            <Plus />
          </el-icon>
          新增
        </el-button>
      
        <el-button @click="handleBatchDelete" class="action-btn delete-btn">
          <el-icon>
            <Delete />
          </el-icon>
          删除
        </el-button>
      </div>
      <div class="utility-icons">
        <el-tooltip :content="showSearchArea ? '隐藏搜索' : '显示搜索'" placement="top">
          <el-icon class="icon-btn" @click="toggleSearchArea" :class="{ 'active': showSearchArea }">
            <Search />
          </el-icon>
        </el-tooltip>
        <el-tooltip content="刷新" placement="top">
          <el-icon class="icon-btn" @click="refreshData">
            <Refresh />
          </el-icon>
        </el-tooltip>
        <el-tooltip content="全屏" placement="top">
          <el-icon class="icon-btn" @click="toggleFullscreen">
            <Expand />
          </el-icon>
        </el-tooltip>    
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-table :data="tableData" v-loading="loading" @selection-change="handleSelectionChange" class="data-table"
        border stripe>
        <el-table-column type="selection" width="55" />
        <el-table-column prop="index" label="序号" width="80" align="center">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="itemCode" label="编码" width="150" align="center">
          <template #header>
            <span>编码</span>
            <el-icon class="search-icon">
              <Search />
            </el-icon>
          </template>
        </el-table-column>
        <el-table-column prop="itemName" label="名称" width="200" align="center">
          <template #header>
            <span>名称</span>
            <el-icon class="search-icon">
              <Search />
            </el-icon>
          </template>
        </el-table-column>
        <el-table-column prop="itemTypeName" label="类型" width="150" align="center">
          <template #header>
            <span>类型</span>
            <el-icon class="search-icon">
              <Search />
            </el-icon>
          </template>
          <template #default="scope">
            <el-tag :type="getTagType(scope.row.itemTypeId)" size="small">
              {{ scope.row.itemTypeName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="routingName" label="默认工艺路线" width="180" align="center">
          <template #header>
            <span>默认工艺路线</span>
            <el-icon class="search-icon">
              <Search />
            </el-icon>
          </template>
        </el-table-column>
        <el-table-column prop="itemMsg" label="描述" min-width="150" align="center" />
        <el-table-column prop="addProp" label="创建人" width="120" align="center" />
        <el-table-column prop="addTime" label="创建时间" width="160" align="center">
          <template #default="scope">

            {{ moment(scope.row.addTime).format("yyyy-MM-DD HH:mm:ss") }}
          </template>

        </el-table-column>
        <el-table-column prop="updTime" label="更新时间" width="160" align="center">
          <template #default="scope">


            {{ moment(scope.row.updTime).format("yyyy-MM-DD HH:mm:ss") }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template #default="scope">
            <el-button type="text" @click="handleEdit(scope.row)" class="action-link">
              编辑
            </el-button>
            <el-button type="text" @click="handleDelete(scope.row)" class="action-link delete-link">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-section">
      <div class="data-summary">
        共{{ total }}条数据
      </div>
      <div class="pagination-controls">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
          :total="total" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" @close="resetForm">
      
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="群组编码" prop="itemCode">
          <el-input v-model="form.itemCode" placeholder="请输入群组编码" />
        </el-form-item>
        <el-form-item label="群组名称" prop="itemName">
          <el-input v-model="form.itemName" placeholder="请输入群组名称" />
        </el-form-item>
        <el-form-item label="群组类型" prop="itemTypeId">
          <el-select v-model="form.itemTypeId" placeholder="请选择群组类型" style="width: 100%"
            @change="handleGroupTypeChange">
            <el-option v-for="item in groupTypes" :key="item.id" :label="item.groupTypeName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="默认工艺路线" prop="routingId" v-if="showProcessRoute">
          <el-select v-model="form.routingId" placeholder="请选择工艺路线" style="width: 100%">
            <el-option v-for="route in processRoutes" :key="route.id" :label="route.routingName" :value="route.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="群组描述" prop="itemMsg">
          <el-input v-model="form.itemMsg" type="textarea" :rows="3" placeholder="请输入群组描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import moment from 'moment'
import {
  Plus,
  Download,
  Delete,
  Grid,
  Search,
  Refresh,
  Expand,
  Setting,
  Close,
  Sort,
  Clock,
  ArrowDown
} from '@element-plus/icons-vue'
import Maxios from '@/Http/MesHelp'

// 接口定义
interface ItemGroup {
  id: number
  itemCode: string
  itemName: string
  itemMsg: string
  itemTypeId: number
  itemTypeName: string
  routingId: number
  routingName: string
  addProp: string
  addTime: string
  updProp?: string
  updTime?: string
}

interface GroupType {
  id: number
  groupTypeName: string
}

interface ProcessRoute {
  id: number
  routingName: string
}

// ==================== 响应式数据定义 ====================
const loading = ref(false) // 表格加载状态
const tableData = ref<ItemGroup[]>([]) // 表格数据
const selectedRows = ref<ItemGroup[]>([]) // 选中的行数据
const currentPage = ref(1) // 当前页码
const pageSize = ref(10) // 每页显示数量
const total = ref(0) // 总数据量
const dialogVisible = ref(false) // 对话框显示状态
const dialogTitle = ref('新增物料群组') // 对话框标题
const isEdit = ref(false) // 是否为编辑模式
const groupTypes = ref<GroupType[]>([]) // 群组类型数据
const processRoutes = ref<ProcessRoute[]>([]) // 工艺路线数据
const showSearchArea = ref(true) // 搜索区域显示状态
const searchHistory = ref<Array<{ ItemCode: string, ItemName: string, ItemTypeId: number | null }>>([]) // 搜索历史记录

// ==================== 表单数据定义 ====================
// 搜索表单数据
const searchForm = reactive({
  itemCode: '', // 群组编码搜索条件
  itemName: '', // 群组名称搜索条件
  itemTypeId: null as number | null // 群组类型搜索条件
})

// 新增/编辑表单数据
const formRef = ref() // 表单引用
const form = reactive({
  id: 0, // 物料群组ID
  itemCode: '', // 群组编码
  itemName: '', // 群组名称
  itemMsg: '', // 群组描述
  itemTypeId: null as number | null, // 群组类型ID - 改为number类型
  routingId: null as number | null, // 工艺路线ID - 改为number类型
  addProp: localStorage.getItem("userNickname") || '' // 创建人
})

// 表单验证规则
const rules = {
  itemCode: [
    { required: true, message: '请输入群组编码', trigger: 'blur' } // 群组编码必填
  ],
  itemName: [
    { required: true, message: '请输入群组名称', trigger: 'blur' } // 群组名称必填
  ],
  itemTypeId: [
    { required: true, message: '请选择群组类型', trigger: 'change' } // 群组类型必选
  ],
  routingId: [
    {
      required: true,
      message: '请选择工艺路线',
      trigger: 'change',
      validator: (rule: any, value: any, callback: any) => {
        if (showProcessRoute.value && !value) {
          callback(new Error('请选择工艺路线'))
        } else {
          callback()
        }
      }
    }
  ]
}

// ==================== API接口方法 ====================
// API基础URL配置
const API_BASE_URL = '/api'  // 后端控制器路由为 api/[controller]/[action]

// 注意：后端已实现三表连接（ItemGroup + GroupType + Routing）
// 分页功能由后端处理，前端只需传递分页参数

// 获取群组类型数据
const getGroupTypes = async () => {
  try {
    const response = await Maxios.post(`${API_BASE_URL}/Band/GroupTypeGet`)
    if (response.data.code === 200) {
      groupTypes.value = response.data.data
    } else {
      ElMessage.error(response.data.message || '获取群组类型失败')
    }
  } catch (error) {
    console.error('获取群组类型失败:', error)
    // 如果API调用失败，使用模拟数据
    groupTypes.value = [
      { id: 1, groupTypeName: '原材料' },
      { id: 2, groupTypeName: '半成品' }, // 根据图片显示，ID=2是半成品
      { id: 3, groupTypeName: '成品' },
      { id: 4, groupTypeName: '上工件' }
    ]
  }
}

// 获取工艺路线数据
const getProcessRoutes = async () => {
  try {
    const response = await Maxios.get(`${API_BASE_URL}/Process/GetProccessRouting`)
    if (response.data.code === 200) {
      processRoutes.value = response.data.data || []
    } else {
      ElMessage.error(response.data.message || '获取工艺路线失败')
    }
  } catch (error) {
    console.error('获取工艺路线失败:', error)
    ElMessage.error('获取工艺路线失败')
  }
}

// 获取物料群组列表数据
const getItemGroups = async () => {
  loading.value = true
  try {
    // 调用后端API获取物料群组数据（包含分页参数）
    const response = await Maxios.post(`${API_BASE_URL}/ItemGroup/ItemGroupQuery`, {
      ItemCode: searchForm.itemCode || null,
      ItemName: searchForm.itemName || null,
      ItemMsg: null,
      ItemTypeId: searchForm.itemTypeId,
      PageIndex: currentPage.value, // 当前页码
      PageSize: pageSize.value // 每页显示数量
    })

    if (response.data.code === 200) {
      const result = response.data.data // 获取分页结果对象

      console.log('API返回数据:', result)

      // 直接使用后端返回的数据（已包含类型名称和工艺路线名称）
      tableData.value = result.data || []
      total.value = result.total || 0
      currentPage.value = result.pageIndex || 1
      pageSize.value = result.pageSize || 10

      console.log('数据设置完成:', {
        total: total.value,
        tableDataLength: tableData.value.length,
        tableData: tableData.value
      })
    } else {
      ElMessage.error(response.data.message || '获取数据失败')
    }
  } catch (error) {
    console.error('获取物料群组失败:', error)
    ElMessage.error('获取物料群组数据失败')
  } finally {
    loading.value = false
  }
}

// ==================== 业务逻辑方法 ====================
// 根据类型ID获取对应的标签样式类型
const getTagType = (typeId: number) => {
  const typeMap: { [key: number]: string } = {
    1: 'danger',    // 原材料
    2: 'primary',   // 半成品
    3: 'success',   // 成品
    4: 'info'       // 上工件
  }
  return typeMap[typeId] || 'info' // 默认返回蓝色标签
}

// 新增物料群组
const handleAdd = () => {
  isEdit.value = false // 设置为新增模式
  dialogTitle.value = '新增物料群组'
  dialogVisible.value = true // 显示对话框
  resetForm() // 重置表单数据
}

// 编辑物料群组
const handleEdit = (row: ItemGroup) => {
  isEdit.value = true // 设置为编辑模式
  dialogTitle.value = '编辑物料群组'
  dialogVisible.value = true // 显示对话框

  // 将行数据填充到表单中，确保字段名匹配
  Object.assign(form, {
    id: row.id,
    itemCode: row.itemCode,
    itemName: row.itemName,
    itemMsg: row.itemMsg,
    itemTypeId: row.itemTypeId, // 直接赋值number类型
    routingId: row.routingId, // 直接赋值number类型
    addProp: row.addProp
  })
}

// 删除单个物料群组
const handleDelete = async (row: ItemGroup) => {
  try {
    // 确认删除操作
    await ElMessageBox.confirm('确定要删除这个物料群组吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    // 调用删除API
    const response = await Maxios.post(`${API_BASE_URL}/ItemGroup/ItemGroupDel`, {
      Id: row.id
    })

    if (response.data.code === 200) {
      ElMessage.success('删除成功')
      getItemGroups() // 刷新数据
    } else {
      ElMessage.error(response.data.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 批量删除物料群组
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的项目')
    return
  }

  try {
    // 确认批量删除操作
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 个项目吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    // 批量删除：逐个调用删除API
    const deletePromises = selectedRows.value.map(row =>
      Maxios.post(`${API_BASE_URL}/ItemGroup/ItemGroupDel`, { Id: row.id })
    )

    await Promise.all(deletePromises)
    ElMessage.success('批量删除成功')
    getItemGroups() // 刷新数据
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 导出物料群组数据（功能待开发）
const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

// 提交表单（新增或编辑物料群组）
const submitForm = async () => {
  if (!formRef.value) return

  try {
    // 表单验证
    await formRef.value.validate()

    // 准备请求数据，确保字段名与后端匹配
    const requestData = {
      Id: form.id || 0,
      ItemCode: form.itemCode,
      ItemName: form.itemName,
      ItemMsg: form.itemMsg || '',
      ItemTypeId: form.itemTypeId || 0,
      RoutingId: showProcessRoute.value ? (form.routingId || 0) : 0,
      AddProp: localStorage.getItem('userNickname') || '',
      UpdProp: isEdit.value ? localStorage.getItem('userNickname') || '' : ''
    }

    console.log('提交数据:', requestData)

    // 根据操作类型调用不同的API
    if (isEdit.value) {
      // 编辑操作：调用更新API
      const response = await Maxios.post(`${API_BASE_URL}/ItemGroup/ItemGroupUp`, requestData)
      if (response.data.code === 200) {
        ElMessage.success(response.data.message || '更新成功')
      } else {
        ElMessage.error(response.data.message || '更新失败')
        return
      }
    } else {
      // 新增操作：调用添加API
      const response = await Maxios.post(`${API_BASE_URL}/ItemGroup/ItemGroupAdd`, requestData)
      if (response.data.code === 200) {
        ElMessage.success(response.data.message || '添加成功')
      } else {
        ElMessage.error(response.data.message || '添加失败')
        return
      }
    }

    dialogVisible.value = false
    getItemGroups() // 刷新数据列表
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('操作失败')
  }
}

// 重置表单数据到初始状态
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields() // 重置表单验证状态
  }
  // 重置表单数据为默认值
  Object.assign(form, {
    id: 0,
    itemCode: '',
    itemName: '',
    itemMsg: '',
    itemTypeId: null, // 改为null
    routingId: null, // 改为null
    addProp: localStorage.getItem("userNickname") || ''
  })
}

// 处理表格行选择变化
const handleSelectionChange = (selection: ItemGroup[]) => {
  selectedRows.value = selection // 更新选中的行数据
}

// 处理分页大小变化
const handleSizeChange = (size: number) => {
  console.log('分页大小变化:', { oldSize: pageSize.value, newSize: size })
  pageSize.value = size // 更新每页显示数量
  currentPage.value = 1 // 重置到第一页
  getItemGroups() // 重新获取数据（后端会处理分页）
}

// 处理当前页码变化
const handleCurrentChange = (page: number) => {
  console.log('页码变化:', { oldPage: currentPage.value, newPage: page })
  currentPage.value = page // 更新当前页码
  getItemGroups() // 重新获取数据（后端会处理分页）
}

// 执行搜索操作
const handleSearch = () => {
  currentPage.value = 1 // 重置到第一页

  // 保存搜索历史记录
  if (hasSearchConditions.value) {
    const currentSearch = {
      ItemCode: searchForm.itemCode,
      ItemName: searchForm.itemName,
      ItemTypeId: searchForm.itemTypeId
    }

    // 避免重复添加相同的搜索条件
    const exists = searchHistory.value.some(item =>
      item.ItemCode === currentSearch.ItemCode &&
      item.ItemName === currentSearch.ItemName &&
      item.ItemTypeId === currentSearch.ItemTypeId
    )

    if (!exists) {
      searchHistory.value.unshift(currentSearch) // 添加到历史记录开头
      // 只保留最近10条搜索历史
      if (searchHistory.value.length > 10) {
        searchHistory.value = searchHistory.value.slice(0, 10)
      }
    }
  }

  getItemGroups() // 执行搜索并获取数据（后端会处理分页和过滤）
}

// 切换搜索区域的显示/隐藏状态
const toggleSearchArea = () => {
  showSearchArea.value = !showSearchArea.value // 切换显示状态
}

// 刷新数据列表
const refreshData = () => {
  getItemGroups() // 重新获取数据
  ElMessage.success('数据已刷新')
}

// 切换浏览器全屏模式
const toggleFullscreen = () => {
  if (!document.fullscreenElement) {
    document.documentElement.requestFullscreen() // 进入全屏
  } else {
    document.exitFullscreen() // 退出全屏
  }
}

// 测试API连接
const testAPI = async () => {
  try {
    console.log('开始测试API连接...')
    console.log('完整URL:', `http://localhost:5293${API_BASE_URL}/ItemGroup/ItemGroupQuery`)

    const response = await Maxios.post(`${API_BASE_URL}/ItemGroup/ItemGroupQuery`, {
      ItemCode: null,
      ItemName: null,
      ItemMsg: null,
      ItemTypeId: null,
      PageIndex: 1,
      PageSize: 10
    })

    console.log('API响应:', response)
    ElMessage.success('API连接成功！')

    // 显示返回的数据结构
    if (response.data && response.data.data) {
      console.log('返回数据结构:', response.data.data)
    }
  } catch (error) {
    console.error('API测试失败:', error)
    ElMessage.error('API连接失败，请检查后端服务')
  }
}

// 测试分页功能
const testPagination = () => {
  console.log('当前分页状态:', {
    currentPage: currentPage.value,
    pageSize: pageSize.value,
    total: total.value,
    tableDataLength: tableData.value.length
  })

  // 测试切换到第二页
  currentPage.value = 2
  getItemGroups()
  ElMessage.info('已切换到第二页进行测试')
}

// 清空搜索条件
const clearSearch = () => {
  searchForm.itemCode = '' // 清空编码搜索条件
  searchForm.itemName = '' // 清空名称搜索条件
  searchForm.itemTypeId = null // 清空类型搜索条件
  handleSearch() // 执行搜索（此时会搜索所有数据）
  ElMessage.success('搜索条件已清空')
}

// 群组类型变化处理
const handleGroupTypeChange = () => {
  // 如果选择的不是成品或半成品，清空工艺路线选择
  if (!showProcessRoute.value) {
    form.routingId = null
  }
}

// ==================== 计算属性 ====================
// 计算属性：检查是否有搜索条件
const hasSearchConditions = computed(() => {
  return searchForm.itemCode || searchForm.itemName || searchForm.itemTypeId // 任一条件有值即为有搜索条件
})

// 是否显示工艺路线字段（只有成品和半成品才显示）
const showProcessRoute = computed(() => {
  return form.itemTypeId === 2 || form.itemTypeId === 3 // 半成品(2)或成品(3)
})

// 获取当前搜索条件的文本描述
const getSearchConditionsText = () => {
  const conditions = []
  if (searchForm.itemCode) conditions.push(`编码: ${searchForm.itemCode}`)
  if (searchForm.itemName) conditions.push(`名称: ${searchForm.itemName}`)
  if (searchForm.itemTypeId) {
    const groupType = groupTypes.value.find(type => type.id === searchForm.itemTypeId)
    conditions.push(`类型: ${groupType ? groupType.groupTypeName : '未知'}`)
  }
  return conditions.join(', ') // 用逗号连接所有条件
}

// 获取搜索历史项的文本描述
const getSearchHistoryText = (item: { ItemCode: string, ItemName: string, ItemTypeId: number | null }) => {
  const conditions = []
  if (item.ItemCode) conditions.push(`编码: ${item.ItemCode}`)
  if (item.ItemName) conditions.push(`名称: ${item.ItemName}`)
  if (item.ItemTypeId) {
    const groupType = groupTypes.value.find(type => type.id === item.ItemTypeId)
    conditions.push(`类型: ${groupType ? groupType.groupTypeName : '未知'}`)
  }
  return conditions.join(', ') || '空搜索' // 如果没有条件则显示"空搜索"
}

// 加载搜索历史记录到搜索表单
const loadSearchHistory = (item: { ItemCode: string, ItemName: string, ItemTypeId: number | null }) => {
  searchForm.itemCode = item.ItemCode // 填充编码搜索条件
  searchForm.itemName = item.ItemName // 填充名称搜索条件
  searchForm.itemTypeId = item.ItemTypeId // 填充类型搜索条件
  handleSearch() // 执行搜索
  ElMessage.success('已加载搜索历史')
}

// 处理键盘快捷键事件
const handleKeydown = (event: KeyboardEvent) => {
  // Ctrl + F 切换搜索区域显示/隐藏
  if (event.ctrlKey && event.key === 'f') {
    event.preventDefault() // 阻止默认行为
    toggleSearchArea()
  }
  // F5 刷新数据
  if (event.key === 'F5') {
    event.preventDefault() // 阻止默认行为
    refreshData()
  }
}

// ==================== 生命周期钩子 ====================
// 组件挂载时初始化数据
onMounted(() => {
  getGroupTypes() // 获取群组类型数据
  getProcessRoutes() // 获取工艺路线数据
  getItemGroups() // 获取物料群组列表数据

  // 添加键盘事件监听器
  document.addEventListener('keydown', handleKeydown)
})

// 组件卸载时清理事件监听器
onUnmounted(() => {
  document.removeEventListener('keydown', handleKeydown) // 移除键盘事件监听器
})
</script>

<style scoped>
.item-group-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.top-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-area {
  flex: 1;
  display: flex;
  gap: 10px;
  align-items: center;
  flex-wrap: wrap;
}

.search-status {
  width: 100%;
  margin-bottom: 10px;
}

.search-input {
  width: 200px;
}

.search-btn {
  display: flex;
  align-items: center;
  gap: 5px;
}

.clear-btn {
  display: flex;
  align-items: center;
  gap: 5px;
}

.history-btn {
  display: flex;
  align-items: center;
  gap: 5px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 5px;
}

.delete-btn {
  background-color: #f56c6c;
  border-color: #f56c6c;
}

.delete-btn:hover {
  background-color: #f78989;
  border-color: #f78989;
}

.utility-icons {
  display: flex;
  gap: 15px;
}

.icon-btn {
  font-size: 18px;
  color: #606266;
  cursor: pointer;
  padding: 5px;
  border-radius: 4px;
  transition: all 0.3s;
}

.icon-btn:hover {
  color: #409eff;
  background-color: #f0f9ff;
}

.icon-btn.active {
  color: #409eff;
  background-color: #f0f9ff;
}

.table-section {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.data-table {
  width: 100%;
}

.search-icon {
  margin-left: 5px;
  font-size: 12px;
  color: #909399;
}

.sort-icon {
  margin-left: 3px;
  font-size: 12px;
  color: #909399;
}

.action-link {
  color: #409eff;
  text-decoration: none;
  margin: 0 5px;
}

.delete-link {
  color: #f56c6c;
}

.pagination-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.data-summary {
  color: #606266;
  font-size: 14px;
}

.pagination-controls {
  display: flex;
  align-items: center;
}

.pagination-controls .el-pagination {
  margin: 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 搜索区域动画 */
.search-slide-enter-active,
.search-slide-leave-active {
  transition: all 0.3s ease;
}

.search-slide-enter-from,
.search-slide-leave-to {
  opacity: 0;
  transform: translateY(-10px);
  max-height: 0;
}

.search-slide-enter-to,
.search-slide-leave-from {
  opacity: 1;
  transform: translateY(0);
  max-height: 100px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .top-section {
    flex-direction: column;
    align-items: stretch;
  }

  .search-input {
    width: 100%;
  }

  .action-buttons {
    justify-content: center;
  }

  .utility-icons {
    justify-content: center;
  }

  .pagination-section {
    flex-direction: column;
    gap: 15px;
  }
}
</style>
